package com.dfd.mango.admin.security;

import com.dfd.mango.admin.entity.SysUser;
import com.dfd.mango.admin.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/*
 *文件名: UserDetailServiceImpl
 *创建者: 东东
 *创建时间:2021/8/18 16:04
 *描述:   登录信息查询
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = userService.findByName(username);
        if (user == null) {
            throw new UsernameNotFoundException("该用户不存在！");
        }
        // 存在
        // 查询当前用户的权限
        Set<String> permissions = userService.findPermissions(username);
        // 封装为集合
        List<GrantedAuthorityImpl> grantedAuthorities = permissions.stream().map(GrantedAuthorityImpl::new).collect(Collectors.toList());
        return new JwtUserDetails(username, user.getPassword(), user.getSalt(), grantedAuthorities);
    }
}
